package com.zelin.gulimall.ware.service.impl;

import com.zelin.common.constant.WareConstant;
import com.zelin.gulimall.ware.entity.PurchaseDetailEntity;
import com.zelin.gulimall.ware.service.PurchaseDetailService;
import com.zelin.gulimall.ware.service.WareInfoService;
import com.zelin.gulimall.ware.service.WareSkuService;
import com.zelin.gulimall.ware.vo.MergeVo;
import com.zelin.gulimall.ware.vo.PurchaseDoneVo;
import com.zelin.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelin.common.utils.PageUtils;
import com.zelin.common.utils.Query;

import com.zelin.gulimall.ware.dao.PurchaseDao;
import com.zelin.gulimall.ware.entity.PurchaseEntity;
import com.zelin.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购单
     * @param vo
     */
    @Override
    public void merge(MergeVo vo) {
        //1.得到采购单id
        Long purchaseId = vo.getPurchaseId();
        //2.判断是否有值,若无值，代表第一次新建
        if(purchaseId == null){
            PurchaseEntity entity = new PurchaseEntity();
            entity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            this.save(entity);
            //3.得到新建的采购单的值
            purchaseId = entity.getId();
        }
        //TODO: 确定采购单状态为0，1才能合并

        //4.遍历采购单详情id（合并项id）
        List<Long> items = vo.getItems();

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(m -> {
            //4.1)定义采购单详情
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(m);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        //4.2) 批量更新
        purchaseDetailService.updateBatchById(collect);

        //5.更新purchase采购单的修改时间
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 查询己创建或己分配的采购单（只要未领取）
     * @param params
     * @return
     */
    @Override
    public PageUtils unreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status","0").or().eq("status","1");
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    //领取采购单
    @Override
    @Transactional
    public void received(List<Long> ids) {
        //1.查询己新建或己分配的采购单
        List<PurchaseEntity> purchaseEntities =
                ids.stream()
         .map(m -> {
            PurchaseEntity purchaseEntity = this.getById(m);
            return purchaseEntity;
            })
         .filter(f ->
                    f.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    f.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
                )
           .map(m -> {
                    m.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    m.setUpdateTime(new Date());
                    return m;
            }).collect(Collectors.toList());
        //2.批量修改采购单
        this.updateBatchById(purchaseEntities);
        //3.修改订单项状态
        purchaseEntities.forEach(m->{
            Long id = m.getId();
            //根据外键purchaseId查询采购单项集合
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.findPurchaseDetailByPurchaseId(id);
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(
                    m1 -> {
                        m1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                        return m1;
                    }
            ).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        });
    }

    /**
     * 完成采购
     * @param vo
     */
    @Override
    @Transactional
    public void purchaseDone(PurchaseDoneVo vo) {
        //1.得到采购单id
        Long id = vo.getId();
        //2.改变采购项的状态
        List<PurchaseItemDoneVo> items = vo.getItems();
        //2.1)定义要改变状态的采购项集合
        List<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        boolean flag = true;
        for(PurchaseItemDoneVo item : items){
            Long itemId = item.getItemId();

            //2.2)查询得到采购项对象
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(itemId);
            //2.3)判断采购项的状态值是否是有异常，如果是就设置标志位
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                detailEntity.setStatus(item.getStatus());
                flag = false;
            }else{  //否则，设置状态值为完成
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //进行商品入库
                wareSkuService.addStock(detailEntity);
            }
            //2.4)将采购项添加到集合中
            detailEntities.add(detailEntity);
        };
        //2.5)批量更新采购项
        purchaseDetailService.updateBatchById(detailEntities);

        //2.6)根据上面的状态值，修改采购单的状态值
        PurchaseEntity purchaseEntity = this.getById(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }

}